<?php
namespace QiyeWork;

use GuzzleHttp\Client;

class QiyeWorkService{

    protected $app = null;
    protected $agentid = null;
    protected $secret = null;
    protected $httpClient = null;
    protected $username = '';
    protected $password = '';
    protected $headers = [];
    protected $config = [];
    protected $corpid = '';
    protected $corpsecret = '';

    const LOGIN_FIAL = 1002;

    protected $baseUrl = 'https://qyapi.weixin.qq.com';
    

    public function __construct($config)
    {
        $this->config = $config;
        $this->corpid = $config['corpid'];
        $this->agentid = $config['agentid'];
        $this->corpsecret = $config['secret'];
        $this->httpClient = new Client([
            'verify' => false,
            'base_uri' => $this->baseUrl,
        ]);
    }


    public function getLoginUrl($redirect_uri, $state = ""){
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->config['corpid'] . '&agentid='.$this->agentid.'&redirect_uri=' . urlencode($redirect_uri) . '&response_type=code&scope=snsapi_privateinfo&state=' . $state . '#wechat_redirect';
        return $url;
    }

    // 获取访问用户身份
    public function getUserInfo($code){
        $result = $this->openRequest(sprintf('/cgi-bin/user/getuserinfo?access_token=%s&code=%s', $this->getAccessToken()['access_token'], $code));
        if(isset($result['errcode']) && $result['errcode'] != 0){
            throw new \Exception($result['errmsg']);
        }
        return $result;
    }


    public function getUser($userId){
        $result = $this->openRequest(sprintf('/cgi-bin/user/get?access_token=%s&userid=%s', $this->getAccessToken()['access_token'], $userId));
        if(isset($result['errcode']) && $result['errcode'] != 0){
            throw new \Exception($result['errmsg']);
        }
        return $result;
    }





    public function getAccessToken($reflash = false){
        $key = 'qiye_work_access_token_' . $this->config['corpid'];
        $result = cache($key);
        if($reflash || !$result){
            $result = $this->openRequest(sprintf('/cgi-bin/gettoken?corpid=%s&corpsecret=%s', $this->corpid, $this->corpsecret));


            if(isset($result['errcode']) && $result['errcode'] != 0){
                // cache($key, $result['access_token'], 7000);
                throw new \Exception($result['errmsg']);
            }

            if(isset($result['access_token']) && $result['access_token']){
                cache($key, $result, $result['expires_in'] - 100);
            }
        }
        return $result;
    }
    //https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN

    // 获取企业的JSAPI Ticket
    public function getJsapiTicket($reflash = false){
        $key = 'qiye_work_jsapi_ticket_' . $this->config['corpid'];
        $result = cache($key);
        if($reflash || !$result){
            $result = $this->openRequest(sprintf('/cgi-bin/get_jsapi_ticket?access_token=%s', $this->getAccessToken()['access_token']));
            if(isset($result['errcode']) && $result['errcode'] != 0){
                throw new \Exception($result['errmsg']);
            }
            if(isset($result['ticket']) && $result['ticket']){
                cache($key, $result, $result['expires_in'] - 100);
            }
        }
        return $result;
    }


    public function getNonceStr(){
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $nonceStr = '';
        for($i = 0; $i < 16; $i++){
            $nonceStr .= $str[mt_rand(0, strlen($str) - 1)];
        }
        return $nonceStr;
    }

    //jsapi_ticket=JSAPITICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL
    // 企业的JSAPI签名
    public function getJsapiSign($url = '', $jsApiList = []){
        $jsapiTicket = $this->getJsapiTicket();
        $noncestr = $this->getNonceStr();
        $timestamp = time();
        $string = sprintf('jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s', $jsapiTicket['ticket'], $noncestr, $timestamp, $url);
        // dump($string);
        $signature = sha1($string);
        return [
            'beta' => true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            'debug'=> true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            'corpid' => $this->config['corpid'],
            'appId' => $this->config['corpid'],
            'agentid' => $this->config['agentid'],
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'url' => $url,
            'jsApiList' => $jsApiList,
        ];
    }

    // 应用的JSAPI签名
    public function getAgentConfigSign($url = '', $jsApiList = []){
        $jsapiTicket = $this->getAgentConfigTicket();
        $noncestr = $this->getNonceStr();
        $timestamp = time();
        $string = sprintf('jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s', $jsapiTicket['ticket'], $noncestr, $timestamp, $url);
        $signature = sha1($string);
        return [
            'beta' => true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            'debug'=> true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            'corpid' => $this->config['corpid'],
            'appId' => $this->config['corpid'],
            'agentid' => $this->config['agentid'],
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'url' => $url,
            'jsApiList' => $jsApiList,
        ];
    }

    //https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=ACCESS_TOKEN&type=agent_config
    // 获取企业的JSAPI Ticket
    public function getAgentConfigTicket($reflash = false){
        $key = 'qiye_work_agent_config_ticket_' . $this->config['corpid'];
        $result = cache($key);
        if($reflash || !$result){
            $result = $this->openRequest(sprintf('/cgi-bin/ticket/get?access_token=%s&type=agent_config', $this->getAccessToken()['access_token']));
            if(isset($result['errcode']) && $result['errcode'] != 0){
                throw new \Exception($result['errmsg']);
            }
            if(isset($result['ticket']) && $result['ticket']){
                cache($key, $result, $result['expires_in'] - 100);
            }
        }
        return $result;
    }


    public function openRequest($url = '', $methods = 'GET', $form_params = [], $return = 'array', $option = [], $reflash_proxy = false, $time = 1)
    {
        $result = false;

        $option['headers'] = $this->headers;
        // $option['proxy'] = "http://127.0.0.1:8888";
        try {
            $response = $this->httpClient->request(
                $methods,
                $url,
                $option
            );
            $contents = $response->getBody()->getContents();
            $result = $return == 'array' ? json_decode($contents, true) : $contents;


        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            // 链接失败、重试,
            echo $e->getMessage();
            $result = false;
        }


        return $result;
    }
 

}